/*
 * Config.java
 *
 * Created on 1 de agosto de 2007, 02:07
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package model;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Hashtable;

/**
 *
 * @author mariano
 */
public class Config {
    private Hashtable<String,String> data;
    private String path; //config path
    /** Creates a new instance of Config */
    public Config(String path) {
        data = new Hashtable<String,String>();
        String config = readTextFile(path);
        config.replaceAll(" ", "");
        String[] lines = config.split("\\n");
        
        for(String line:lines)
        {
            String values[] = line.split(":", 2);
            
            if(values.length == 2)
            {
                data.put(values[ 0 ].replaceAll("%20", " "), values[ 1 ].replaceAll("%20", " "));
            }
        }
    }
    
    public Config()
    {
        this("./config");
    }
    
    public String getValue(String key, String defaultValue)
    {
        if(data.containsKey(key))
            return data.get(key);
        
        return defaultValue;
    }
    
    public void setValue(String key, String value)
    {
        data.put(key,value);
    }
    
    public void save() throws FileNotFoundException, IOException
    {
        StringBuffer sb = new StringBuffer();
        
        for(String key:data.keySet())
        {
            sb.append( key.replaceAll(" ", "%20") + ":" + data.get(key).replaceAll(" ", "%20") + "\n" );
        }
        
        writeTextFile(path,sb.toString());
    }
    
    private void writeTextFile( String path, String text ) throws FileNotFoundException, IOException
    {
        FileOutputStream fout;		
        fout = new FileOutputStream (path);
        new PrintStream(fout).print(text);
        fout.close();		
    }
    
    private String readTextFile( String path )
    {
        StringBuffer sb = new StringBuffer();
        
        try
        {
            BufferedReader in = new BufferedReader(new FileReader( path ));
            
            String str;
            while ((str = in.readLine()) != null)
            {
                sb.append(str);
            }
            
            in.close();
        }
        catch (IOException e)
        {
            return "";
        }
        
        return sb.toString();
    }
}
